package xiaoqianlang.filter;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

/**
 * @Author：xiaoqianlang
 * @Package：xiaoqianlang.filter
 * @Project：PasswordManage
 * @name：JwtTokenFilter
 * @Date：2025/4/3/周四 23:08
 * @Filename：JwtTokenFilter
 */
public class JwtTokenFilter extends OncePerRequestFilter {

    private final String secretKey; // 用于签名和验证 JWT 的密钥

    public JwtTokenFilter(String secretKey) {
        this.secretKey = secretKey;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            // 从请求头中获取 JWT Token
            String token = request.getHeader("Authorization");
            if (token != null && token.startsWith("Bearer ")) {
                token = token.substring(7); // 去掉 "Bearer " 前缀

                // 解析并验证 Token
                Claims claims = Jwts.parser() // 使用 parserBuilder()
                        .setSigningKey(secretKey.getBytes()) // 设置密钥为字节数组
                        .build()
                        .parseClaimsJws(token) // 解析 JWT
                        .getBody();

                // 获取用户名
                String username = claims.getSubject();

                // 设置认证信息到 SecurityContext 中
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(username, null, new ArrayList<>());
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        } catch (Exception e) {
            // 如果 Token 验证失败，返回 401 Unauthorized
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            response.getWriter().write("无效的 Token！");
            return;
        }

        // 继续执行后续过滤器链
        filterChain.doFilter(request, response);
    }
}